﻿using AutoMapper;
using MediatR;
using SmartTracking.API.Write.Application.Commands.Permission_command;
using SmartTracking.Domain.UserInfo;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace SmartTracking.API.Write.Application.CommandHandlers.Permission_handler
{
    public class AddPermissionCommandHandler:IRequestHandler<AddPermissionCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<Permissions> permissionRep;
        private readonly IBaseRepository<RolePermissionsMiddle> rolePermissionRep;
        private readonly IMapper mapper;

        public AddPermissionCommandHandler(
            IBaseRepository<Permissions> permissionRep,
            IBaseRepository<RolePermissionsMiddle> rolePermissionRep,
            IMapper mapper)
        {
            this.permissionRep = permissionRep;
            this.rolePermissionRep = rolePermissionRep;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(AddPermissionCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.Code = ApiEnum.新增成功;
            result.Message = ApiEnum.新增成功.ToString();

            
            try
            {
                #region 添加权限
                Permissions permissions = mapper.Map<Permissions>(request);
                permissions.IsDeleted = false;
                permissions.PermissionLevenl = 1;
                permissions.PermissionType = "1";
                permissions.PermissionValue = "1";
                permissions.ParentId = 1;
                var list = await permissionRep.AddAsync(permissions);
                #endregion

                result.data = list;
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.新增失败;
                result.Message = ApiEnum.新增失败.ToString() +","+ ex.Message;
                throw;
            }
            return await Task.FromResult(result);
        }
    }
}
